package middle;

/**
 * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
 *
 * 百度百科中最近公共祖先的定义为：“对于有根树 T 的两个节点 p、q，最近公共祖先表示为一个节点 x
 * 满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”
 *
 * 链接：https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree
 * @author 胡宇轩
 * @Email: programboy@163.com
 */
public class LowestCommonAncestorOfABinaryTree {
    class Solution {
        TreeNode result = null;
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            recur(root, p, q);
            return result;
        }

        private boolean recur(TreeNode root, TreeNode p, TreeNode q) {
            if (root == null) {
                return false;
            }
            boolean recurLeft = recur(root.left, p, q);
            boolean recurRight = recur(root.right, p, q);
            if (recurLeft && recurRight || ((root == p || root == q) && (recurLeft || recurRight)) ) {
                result = root;
            }
            return (root == p || root == q) || recurLeft || recurRight;
        }
    }
}
